package com.multireactor;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SubReactor implements Runnable{
    private ThreadPoolExecutor executor =new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    private final Selector selector;
    private final ServerSocketChannel serverSocketChannel;

    public SubReactor(Selector selector, ServerSocketChannel serverSocketChannel) {
        System.out.println("子Reactor，着手处理"+selector);
        this.selector = selector;
        this.serverSocketChannel = serverSocketChannel;
    }

    @Override
    public void run() {
        try {
            while (true) {
                System.out.println("准备轮询了"+selector);
                if (selector.select() > 0) {
                    System.out.println("轮询到数据");
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    if(iterator.hasNext()){
                        SelectionKey sk = iterator.next();
                        iterator.remove();
                        dispatch(sk);
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    private void dispatch(SelectionKey sk) {
        if(sk.attachment()!=null){
            Runnable handler = (Runnable) sk.attachment();
//            handler.run();
            executor.execute(handler);
        }
    }

}
